﻿using System;
using System.Web.Mvc;
using Account.IService.Entry;
using System.Configuration;
using System.Web;
using FrontCenter.Models;
using Framework.Common.Event;
using Framework.MVC;
using Identity.IService.Entry;
using FrontCenter.Expand;

namespace FrontCenter.Controllers
{
    public class AccountController : AsyncControllerBase
    {
        private static readonly double m_minutes = double.Parse(ConfigurationManager.AppSettings["UserIdentityMinutes"]);
        private readonly static string m_identity_error = ConfigurationManager.AppSettings["IdentityErrorPage"];
        private readonly static string m_usercenterindex = ConfigurationManager.AppSettings["usercenterindex"];
        private readonly static string m_usercenterlogout = ConfigurationManager.AppSettings["usercenterlogout"];
        private const string m_user_resource = "u000";
        private const string m_user_name = "name";
        private const string m_pwd_resource = "modifypassword";
        private const string m_rpwd_resource = "getpassword";
        private const char m_split = ';';
        private const string m_resource = "verifycode";
        private const string m_mark = "_mark";

        private const string m_mobile = "Mobile";
        private const string m_default = "Default";

        #region temp

        private static readonly System.Text.RegularExpressions.Regex m_account = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9]{6,16}$", System.Text.RegularExpressions.RegexOptions.Compiled);
        private static readonly System.Text.RegularExpressions.Regex m_password = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9_]{6,14}$", System.Text.RegularExpressions.RegexOptions.Compiled);

        #endregion temp

        #region Index

        public void IndexAsync(string code,string callback)
        {
            GetAccountModel model = new GetAccountModel
            {
                IdentityCode = code,
                Source = Request.UserHostAddress
            };
            AsyncManager.Parameters["callback"] = callback;
            InitModel(model);
        }

        public ActionResult IndexCompleted(string code,string name,string callback)
        {
            if (string.IsNullOrWhiteSpace(name))
                if(string.IsNullOrWhiteSpace(callback))
                    return RedirectToAction("login", "usercenter");
                else
                    return Redirect(callback);

            HttpCookie userCookie = new HttpCookie(m_user_resource, code);
            HttpCookie nameCookie = new HttpCookie("name", name);
            Response.AppendCookie(userCookie);
            Response.AppendCookie(nameCookie);

            return RedirectToAction("MyInfoAsync");
        }

        #endregion Index

        //我的信息
        #region MyInfo

        public void MyInfoAsync(string code,string _resource) {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user == null || string.IsNullOrWhiteSpace(user.Value) ? code : user.Value;
            MyInfoModel model = new MyInfoModel
            {
                IdentityCode = current,
                Source = Request.UserHostAddress,
                AccountResource = _resource
            };
            ViewData["code"] = current;
            InitModel(model);
        }

        public ActionResult MyInfoCompleted(bool user,UserMailEntry usermail, bool answers, bool mobile,string account,string error)
        {
            ViewData["user"] = user;
            ViewData["mail"] =usermail==null?string.Empty: usermail.address;
            ViewData["answers"] = answers;
            ViewData["name"] = account;
            ViewData["mobile"] = mobile;
            ViewData["error"] = error;
            return View();
        }

        #endregion MyInfo

        //修改资料的view
        #region modifyinfo

        public void ModifyinfoAsync(string code)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user == null || string.IsNullOrWhiteSpace(user.Value) ? code : user.Value;
            ContainsUserInfoModel model = new ContainsUserInfoModel
            {
                IdentityCode = current,
                Source = Request.UserHostAddress
            };
            ViewData["code"] = current;
            InitModel(model);
        }
        public ActionResult ModifyinfoCompleted(bool entry,string error)
        {
            ViewData["error"] = error;
            return View(entry);
        }

        #endregion modifyinfo

        //添加个人资料
        #region addbaseinfo

        public void AddBaseInfoAsync(string code, string year, string month, string province, string phonenum)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            NewUserInfoModel model = new NewUserInfoModel
            {
                IdentityCode = string.IsNullOrWhiteSpace(code) ? (user != null ? user.Value : null) : code,
                Birthday = year + "-" + month,
                Location = province,
                FixedPhone = phonenum,
                Mobile="",
                Source = Request.UserHostAddress
            };

            InitModel(model);
        }
        public ActionResult AddBaseInfoCompleted(UserInfoEntry entry)
        {
            return Json(entry.birthday);
        }

        #endregion addbaseinfo

        //新登录界面
        #region NewLoginIndex

        public void NewLoginIndexAsync(string code, string mark, string _resource)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user == null || string.IsNullOrWhiteSpace(user.Value) ? code : user.Value;

            MyInfoModel model = new MyInfoModel
            {
                IdentityCode = current,
                Source = Request.UserHostAddress,
                AccountResource = !string.IsNullOrWhiteSpace(_resource) ? _resource : "Default"
            };
            InitModel(model);
            
        }
        public ActionResult NewLoginIndexCompleted( string account)
        {
            ViewData["name"] = account;
            return View();
        }

        #endregion NewLoginIndex

        #region Validate

        public void ValidateAsync(string name, string password, string source, string mark, string resource,string _resource)
        {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(password) || !m_account.IsMatch(name) || !m_password.IsMatch(password))
            {
                return;
            }
            ValidateAccountModel model = new ValidateAccountModel
            {
                AccountName=name,
                AccountPassword=password,
                IdentityResource = m_user_resource,
                Mark = mark,
                SourceCode=resource,
                Address = source,
                Source = source,
                AccountResource = _resource
            };
            InitModel(model);
        }

        public ActionResult ValidateCompleted(IdentityEntry entry,string error)
        {
            return Json(entry == null ? error : entry.code);
        }

        #endregion Validate

        #region NewAccount

        public void NewAccountAPIAsync(string name,string password,string source,string mark,string resource) {
            if (string.IsNullOrWhiteSpace(name) || string.IsNullOrWhiteSpace(password) || !m_account.IsMatch(name) || !m_password.IsMatch(password))
            {
                return;
            }
            NewAccountAPIMode model = new NewAccountAPIMode
            {
                AccountName = name,
                AccountPassword=password,
                Mark=mark,
                SourceCode = resource,
                Address=source,
                Source = source
            };
            InitModel(model);
        }

        public ActionResult NewAccountAPICompleted(IdentityEntry entry, string error)
        {
            return Content(entry == null ? error : entry.code);
        }

        #endregion NewAccount

        #region Contains

        public void ContainsAsync(string name,string source,string _resource)
        {
            if (string.IsNullOrWhiteSpace(name) || !m_account.IsMatch(name)) {
                return;
            }
            ContainsAccountModel model = new ContainsAccountModel
            {
                AccountName = name,
                Source = source,
                AccountResource = _resource
            };
            InitModel(model);
        }

        public ActionResult ContainsCompleted(bool result)
        {
            return Content(result.ToString());
        }

        #endregion Contains

        #region NewAUM

        public void NewAUMAsync(string name, string password, string username, string card, string email, string verifycode, string verifyvalue, string _mark, string _resource)
        {
            HttpCookie verifycodeCookies = Request.Cookies[m_resource];
            NewAUMModel model = new NewAUMModel
            {
                VerifyCode = verifycodeCookies == null || string.Equals(_resource, m_mobile) ?  name:verifycodeCookies.Value ,
                Source=Request.UserHostAddress,
                VerifyValue = verifyvalue,
                UserCardID = card,
                UserName = username,
                UserMailAddress = email,
                AccountName = name,
                AccountPassword = password,
                Mark=_mark,
                SourceCode = "platform",
                Address = Request.UserHostAddress,
                AccountResource = _resource
            };
            InitModel(model);
        }

        public ActionResult NewAUMCompleted(string code, string identity,string error)
        {
            return Json(string.IsNullOrWhiteSpace(error) ? identity : error);
        }
        

        #endregion NewAUM

        #region Modify Password View

        public void ModifyPasswordViewAsync(string code,string resource)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = user == null || string.IsNullOrWhiteSpace(user.Value) ? code : user.Value;
            ValidateIdentityModel model = new ValidateIdentityModel
            {
                IdentityCode = current,
                IdentityResource = resource == null ? m_user_resource : m_pwd_resource,
                Source = Request.UserHostAddress
            };
            ViewData["code"] = current;
            InitModel(model);
        }

        public ActionResult ModifyPasswordViewCompleted(IdentityEntry entry,string resource)
        {
            ViewData["contains"] = entry != null;
            return string.Equals(resource, m_user_resource) ? View() : View("ModifyPasswordSafeView");
        }

        #endregion Modify Password View

        #region Login

        public void LoginAsync(string name, string password, string _mark, string verifycode, string verifyvalue, string _resource)
        {
            HttpCookie verifycodeCookies = Request.Cookies[m_resource];
            LoginModel model = new LoginModel
            {
                AccountName = name,
                AccountPassword = password,
                Source=Request.UserHostAddress,
                Address = Request.UserHostAddress,
                SourceCode = "platform",
                Mark = _mark,
                VerifyCode = verifycodeCookies != null ? verifycodeCookies.Value : verifycode,
                VerifyValue = verifyvalue,
                AccountResource = "Default"
            };
            InitModel(model);
        }

        public ActionResult LoginCompleted(string code, string error)
        {
            return Json(string.IsNullOrWhiteSpace(error) ? code : error);
        }

        #endregion Login

        #region Modify Password

        public void ModifyPasswordAsync(string code, string newpassword, string oldpassword, string verifycode, string verifyvalue, string _resource, string resource)
        {
            //HttpCookie pwd = Request.Cookies[m_pwd_resource];
            //if (pwd == null && !string.IsNullOrWhiteSpace(code))
            //    pwd = new HttpCookie(m_pwd_resource, code);
            //HttpCookie user = Request.Cookies[m_user_resource];
            HttpCookie verifycodeCookies = Request.Cookies[m_resource];

            ModifyAccountModel model = new ModifyAccountModel {
                AccountPassword=newpassword,
                OldAccountPassword=oldpassword,
                Source= Request.UserHostAddress,
                IdentityCode = code,
                Resource = resource == null ? m_user_resource : m_pwd_resource,
                VerifyCode = verifycodeCookies != null ? verifycodeCookies.Value : verifycode,
                VerifyValue = verifyvalue,
                IsOnce = true,
                AccountResource = _resource
            };

            InitModel(model);

        }

        public ActionResult ModifyPasswordCompleted(bool result, string error)
        {
            return Json(result ? result.ToString() : error);
        }

        #endregion Modify Password

        #region Logout

        public void LogoutAsync(string code,string callback)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            DeleteIdentityModel model = new DeleteIdentityModel {
                IdentityCode = user == null ? code : user.Value,
                IdentityResource = m_user_resource,
                Source = Request.UserHostAddress
            };
            AsyncManager.Parameters["callback"] = !string.IsNullOrWhiteSpace(callback) ? callback : m_identity_error;
            InitModel(model);
        }

        public ActionResult LogoutCompleted(Identity.IService.Entry.IdentityEntry entry, string callback)
        {
            ViewData["callback"] = callback;
            return View();
        }

        #endregion Logout

        #region New Password Identity

        public void NewPwdIdentityAsync(string name, string verifycode, string verifyvalue, string _resource)
        {
            HttpCookie verifycodeCookies = Request.Cookies[m_resource];
            NewPwdIdentityModel model = new NewPwdIdentityModel
            {
                AccountName = name,
                Source = Request.UserHostAddress,
                VerifyCode = verifycodeCookies != null ? verifycodeCookies.Value : verifycode,
                VerifyValue = verifyvalue,
                IsOnce = true,
                AccountResource = _resource
            };
            InitModel(model);
        }

        public ActionResult NewPwdIdentityCompleted(string code,string error)
        {
            return Json(error??code);
        }

        #endregion New Password Identity

        #region New Modify Password

        public void NewModifyPasswordAsync(string code, string password, string verifycode, string verifyvalue, string _resource, string resource)
        {
            HttpCookie verifycodeCookies = Request.Cookies[m_resource];

            ModifyAccountModel model = new ModifyAccountModel
            {
                AccountPassword = password,
                Source = Request.UserHostAddress,
                IdentityCode = code,
                Resource = resource == null ? m_pwd_resource:m_user_resource,
                VerifyCode = verifycodeCookies != null ? verifycodeCookies.Value : verifycode,
                VerifyValue = verifyvalue,
                IsOnce = true,
                AccountResource = _resource
            };

            InitModel(model);

        }

        public ActionResult NewModifyPasswordCompleted(bool result, string error)
        {
            return Json(result ? result.ToString() : error);
        }

        #endregion New Modify Password

        #region Password Mail

        public void PasswordMailAsync(string code)
        {
            PasswordMailModel model = new PasswordMailModel
            {
                IdentityCode = code,
                IdentityResource = m_rpwd_resource,
                Source = Request.UserHostAddress,
                Resource = m_pwd_resource
            };
            InitModel(model);
        }

        public ActionResult PasswordMailCompleted(IdentityEntry entry,string error)
        {
            return Json(error ?? "resultsuccess");
        }

        #endregion Password Mail

        #region GetPassword By Phone

        public void PasswordPhoneAsync(string code, string verifyvalue)
        {
            ValidateMobileModel model = new ValidateMobileModel
            {
                IdentityCode = code,
                VerifyValue=verifyvalue,
                Source = Request.UserHostAddress
            };
            InitModel(model);
        }

        public ActionResult PasswordPhoneCompleted(IdentityEntry entry, string error)
        {
            return Json(error ?? entry.code);
        }

        #endregion GetPassword By Phone

        #region Transit

        public void TransitAsync(string code, string callback)
        {
            HttpCookie user = Request.Cookies[m_user_resource];
            string current = !string.IsNullOrWhiteSpace(code) ? code : (user!=null?user.Value:null);
            GetAccountModel model = new GetAccountModel
            {
                IdentityCode = current,
                AccountResource = m_default,
                Source = Request.UserHostAddress
            };
            AsyncManager.Parameters["callback"] = !string.IsNullOrWhiteSpace(callback) ? callback : m_usercenterindex;
            InitModel(model);
        }

        public ActionResult TransitCompleted(string code, string name,string callback)
        {
            if (!string.IsNullOrEmpty(code) && !string.IsNullOrEmpty(name))
            {
                HttpCookie usercode = new HttpCookie(m_user_resource, code);
                HttpCookie username = new HttpCookie(m_user_name, name);
                usercode.HttpOnly = true;
                username.HttpOnly = true;
                usercode.Expires = DateTime.Now.AddMinutes(m_minutes);
                username.Expires = DateTime.Now.AddMinutes(m_minutes);
                Response.AppendCookie(usercode);
                Response.AppendCookie(username);
            }
            return Redirect(callback);
        }

        #endregion GetPassword By Phone
    }
}
